//
//  SearchResultVC.m
//  MyNewProject
//
//  Created by 王春辉 on 2020/1/3.
//  Copyright © 2020年 sun. All rights reserved.
//

#import "SearchResultVC.h"
#import "ClassifySectionCell.h"
#import "ProductDetailVC.h"

#pragma mark -- mark Model
#import "ProductModel.h"

@interface SearchResultVC ()<UICollectionViewDelegate, UICollectionViewDataSource, UITextFieldDelegate> {
    NSInteger _page;
}
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSArray <ProductDetailModel *>*dataArray;
@end
static NSString *const identifier = @"pt_identifier";
@implementation SearchResultVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self hideNavLine];
    self.gk_navTitle = @"商城";
//    [self addRightItemBarButton];
    [self initContentViews];
    [self requestData]; // 线获取一页
}

/// 右侧导航栏按钮
- (void)addRightItemBarButton {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"shop_share_bar_btn_img"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(shareBarButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:btn];
    [self setGk_navRightBarButtonItem:barButton];
}

- (void)initContentViews {
    UIView *searchView = [[UIView alloc] init];
    searchView.backgroundColor = SKColorWithHex(0xF2F2F2);
    searchView.layer.masksToBounds = true;
    searchView.layer.cornerRadius = 4.0;
    [self.view addSubview:searchView];
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(searchView.mas_width).multipliedBy(42.0/345);
        make.top.mas_offset(GK_STATUSBAR_NAVBAR_HEIGHT);
    }];
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [searchBtn setImage:SKIMAGE_NAMED(@"shop_search_btn_img") forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(searchButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [searchView addSubview:searchBtn];
    [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.centerY.mas_offset(0);
        make.size.mas_equalTo(CGSizeMake(20, 20));
    }];
    [searchView addSubview:self.textField];
    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(searchBtn.mas_right).mas_offset(15);
        make.top.bottom.mas_offset(0);
        make.right.mas_offset(-15);
    }];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_equalTo(searchView.mas_bottom).mas_offset(15);
        make.bottom.mas_offset(-SKBottomSafe_Height);
    }];
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestData)];
    self.collectionView.mj_footer = [MJRefreshBackStateFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestMoreData)];
}

#pragma mark -- mark 懒加载

- (UITextField *)textField {
    if (!_textField) {
        _textField = [[UITextField alloc] initWithFrame:CGRectZero];
        _textField.placeholder = @"请输入商品名称和分类";
        _textField.font = SKFONT_SIZE(16);
        _textField.textColor = SKColorWithHex(0x333333);
        _textField.returnKeyType = UIReturnKeySearch;
        _textField.delegate = self;
    }
    return _textField;
}
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat margin = 15.0;
        CGFloat centerMargin = 5.0;
        CGFloat width = (self.view.width - margin * 2 - centerMargin) * 0.5;
        CGFloat height = width / 170.0 * 228;
        layout.itemSize = CGSizeMake(width, height);
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.minimumLineSpacing = centerMargin;
        layout.minimumInteritemSpacing = centerMargin;
        layout.sectionInset = UIEdgeInsetsMake(0, margin, centerMargin, margin);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.showsVerticalScrollIndicator = false;
        _collectionView.showsHorizontalScrollIndicator = false;
        [_collectionView registerClass:[ClassifySectionCell class] forCellWithReuseIdentifier:identifier];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = self.view.backgroundColor;
        _collectionView.scrollEnabled = true;
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}


#pragma mark -- mark UICollectionViewDelegate UICollectionViewDataSource

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 详情
    ClassifySectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    ProductDetailModel *model = self.dataArray[indexPath.item];
    cell.title = model.name;
    cell.price = model.price;
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.img] placeholderImage:SKIMAGE_NAMED(@"cell_default_img")];
    SKWeakSelf;
    cell.shareButtonClickBlock = ^{
        [weakSelf cellShareButtonClick:indexPath];
    };
    return cell;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self showProductDetailWith:indexPath];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.textField endEditing:true];
}

#pragma mark -- mark UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.text.length > 0) {
        [self requestData];
        return true;
    }
    [self showMessage:@"请输入你要搜索信息关键字"];
    return false;
}

#pragma mark -- mark 网络请求

/**
 获取首页数据
 */
- (void)requestData {
    _page = 1;
    SKWeakSelf;
    [self requestDataWithKey:self.textField.text Page:_page Success:^(ProductModel *model) {
        weakSelf.dataArray =  model.data;
        [weakSelf.collectionView reloadData];
    } Failed:^(NSString *message) {
        [weakSelf showMessage:message];
    }];
}

/**
 上拉加载
 */
- (void)requestMoreData {
    if (!_page) {
        return; }
    _page++;
    SKWeakSelf;
    [self requestDataWithKey:self.textField.text Page:_page Success:^(ProductModel *model) {
        NSMutableArray *mArr = [NSMutableArray<ProductDetailModel *> arrayWithArray:weakSelf.dataArray];
        [mArr addObjectsFromArray:model.data];
        weakSelf.dataArray = mArr;
        [weakSelf.collectionView reloadData];
    } Failed:^(NSString *message) {
        [weakSelf showMessage:message];
    }];
}

/**
 获取数据

 @param key key
 @param page page
 */
- (void)requestDataWithKey:(NSString *)key Page:(NSInteger)page Success:(void(^)(ProductModel *))successBlock Failed:(void(^)(NSString *))failedBlock {
    [self.textField endEditing:true];
    /*
     type_two_id    int    false    普通参数        二级分类编号
     search_key    string    false    普通参数        搜索关键字
     label_id    int    false    普通参数        标签编号
     page
     */
    SKWeakSelf;
    [YQNetworking getWithUrl:@"Shop/getGoodsList" params:@{@"search_key":key, @"page":@(page)} reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        ProductModel *model = [ProductModel modelWithDictionary:response];
        if ([model isSuccess]) {
            if (successBlock) {
                successBlock(model); }
        }else {
            if (failedBlock) {
            failedBlock(model.msg); }
        }
        if ([weakSelf.collectionView.mj_header isRefreshing]) {
            [weakSelf.collectionView.mj_header endRefreshing];
        }
        if ([weakSelf.collectionView.mj_footer isRefreshing]) {
            [weakSelf.collectionView.mj_footer endRefreshing];
        }
    } failBlock:^(NSError *error) {
        [weakSelf debugShowMessage:error.localizedDescription];
        if ([weakSelf.collectionView.mj_header isRefreshing]) {
            [weakSelf.collectionView.mj_header endRefreshing];
        }
        if ([weakSelf.collectionView.mj_footer isRefreshing]) {
            [weakSelf.collectionView.mj_footer endRefreshing];
        }
    }];
}
#pragma mark -- mark EVENT

/**
 分享按钮

 @param sender sender
 */
- (void)shareBarButtonClick:(UIButton *)sender {
    
}

/**
 搜索按钮

 @param sender sender
 */
- (void)searchButtonClick:(UIButton *)sender {
    [self requestData];
}

#pragma mark -- mark 业务逻辑


/**
 cell 分享按钮点击回调
 
 @param indexPath indexPath
 */
- (void)cellShareButtonClick:(NSIndexPath *)indexPath {
    
}


/**
 查看商品详情
 
 @param indexPath indexPath
 */
- (void)showProductDetailWith:(NSIndexPath *)indexPath {
    ProductDetailModel *model = self.dataArray[indexPath.item];
    if (model.ptId.length > 0) {
        ProductDetailVC *vc = [[ProductDetailVC alloc] init];
        vc.type = 0;
        vc.ptId = model.ptId;
        vc.showType = ProductDetailTypeDetail;
        [self.navigationController pushViewController:vc animated:YES];
    }else {
        [self showMessage:@"无效的数据信息"];
    }
}

@end
